#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <random>
#include <chrono>
#include <iomanip>
#include <thread>

// 简化版的缓存演示程序
// 演示基本的LRU缓存功能，不依赖文件系统

#include "lru_cache.h"
#include "memory_cache.h"

// 简单的测试数据结构
struct SimpleData {
    int id;
    std::string content;

    SimpleData() : id(0), content("") {}
    SimpleData(int i) : id(i), content("Data_" + std::to_string(i)) {}
};

// 基础LRU缓存测试
void testBasicLRU() {
    std::cout << "\n===== 基础LRU缓存测试 =====" << std::endl;

    // 创建容量为5的LRU缓存
    LRUCache<int, SimpleData> cache(5);

    std::cout << "\n1. 插入5个元素..." << std::endl;
    for (int i = 1; i <= 5; ++i) {
        cache.put(i, SimpleData(i));
        std::cout << "  插入: key=" << i << ", content=Data_" << i << std::endl;
    }

    std::cout << "\n2. 访问key=2（将其移到最前面）..." << std::endl;
    SimpleData value;
    if (cache.get(2, value)) {
        std::cout << "  找到: id=" << value.id << ", content=" << value.content << std::endl;
    }

    std::cout << "\n3. 插入第6个元素（应淘汰最久未使用的key=1）..." << std::endl;
    cache.put(6, SimpleData(6));
    std::cout << "  插入: key=6" << std::endl;

    std::cout << "\n4. 验证key=1是否被淘汰..." << std::endl;
    bool found = cache.contains(1);
    std::cout << "  key=1 " << (found ? "存在（错误）" : "不存在（正确，已被淘汰）") << std::endl;

    std::cout << "\n5. 当前缓存统计:" << std::endl;
    std::cout << "  缓存大小: " << cache.size() << "/" << cache.capacity() << std::endl;
    std::cout << "  命中率: " << (cache.getHitRate() * 100) << "%" << std::endl;
    std::cout << "  命中次数: " << cache.getHitCount() << std::endl;
    std::cout << "  未命中次数: " << cache.getMissCount() << std::endl;
}

// 内存缓存测试
void testMemoryCache() {
    std::cout << "\n===== 内存缓存（L1）测试 =====" << std::endl;

    // 创建容量为100，最大内存10MB的缓存
    MemoryCache<std::string, std::vector<int>> cache(100, 10);

    // 设置大小估算器
    cache.setSizeEstimator([](const std::vector<int>& vec) -> size_t {
        return vec.size() * sizeof(int) + sizeof(std::vector<int>);
    });

    std::cout << "\n1. 插入不同大小的向量..." << std::endl;
    for (int i = 0; i < 20; ++i) {
        std::vector<int> vec(100 * (i + 1));  // 不同大小的向量
        for (size_t j = 0; j < vec.size(); ++j) {
            vec[j] = i * 1000 + j;
        }
        cache.put("vector_" + std::to_string(i), vec);
    }

    std::cout << "\n2. 测试缓存访问..." << std::endl;
    std::vector<int> retrieved;
    int hits = 0;
    for (int i = 0; i < 30; ++i) {
        if (cache.get("vector_" + std::to_string(i % 20), retrieved)) {
            hits++;
        }
    }
    std::cout << "  访问30次，命中" << hits << "次" << std::endl;

    // 打印统计信息
    cache.printStatistics();
}

// 性能基准测试
void performanceBenchmark() {
    std::cout << "\n===== 性能基准测试 =====" << std::endl;

    const int num_operations = 100000;
    const int cache_size = 1000;
    const int data_range = 5000;

    MemoryCache<int, std::string> cache(cache_size, 100);

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, data_range - 1);

    // 预热
    std::cout << "\n预热缓存..." << std::endl;
    for (int i = 0; i < cache_size; ++i) {
        cache.put(i, "Value_" + std::to_string(i));
    }

    // 测试写入性能
    std::cout << "\n测试写入性能（" << num_operations << "次操作）..." << std::endl;
    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < num_operations; ++i) {
        int key = dis(gen);
        cache.put(key, "Value_" + std::to_string(key));
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    double ops_per_sec = (num_operations * 1000.0) / duration.count();

    std::cout << "  写入耗时: " << duration.count() << " ms" << std::endl;
    std::cout << "  写入吞吐量: " << std::fixed << std::setprecision(2)
              << ops_per_sec << " ops/sec" << std::endl;

    // 测试读取性能
    std::cout << "\n测试读取性能（" << num_operations << "次操作）..." << std::endl;
    start = std::chrono::high_resolution_clock::now();
    int read_hits = 0;
    for (int i = 0; i < num_operations; ++i) {
        int key = dis(gen);
        std::string value;
        if (cache.get(key, value)) {
            read_hits++;
        }
    }
    end = std::chrono::high_resolution_clock::now();
    duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    ops_per_sec = (num_operations * 1000.0) / duration.count();

    std::cout << "  读取耗时: " << duration.count() << " ms" << std::endl;
    std::cout << "  读取吞吐量: " << std::fixed << std::setprecision(2)
              << ops_per_sec << " ops/sec" << std::endl;
    std::cout << "  实际命中率: " << (read_hits * 100.0 / num_operations) << "%" << std::endl;

    // 测试混合负载
    std::cout << "\n测试混合负载（70%读取，30%写入）..." << std::endl;
    std::uniform_int_distribution<> op_dis(1, 10);
    start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < num_operations; ++i) {
        int key = dis(gen);
        if (op_dis(gen) <= 7) {  // 70%读取
            std::string value;
            cache.get(key, value);
        } else {  // 30%写入
            cache.put(key, "Value_" + std::to_string(key));
        }
    }
    end = std::chrono::high_resolution_clock::now();
    duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    ops_per_sec = (num_operations * 1000.0) / duration.count();

    std::cout << "  混合操作耗时: " << duration.count() << " ms" << std::endl;
    std::cout << "  混合吞吐量: " << std::fixed << std::setprecision(2)
              << ops_per_sec << " ops/sec" << std::endl;

    // 最终统计
    cache.printStatistics();
}

// 并发测试（使用多个线程）
void concurrencyTest() {
    std::cout << "\n===== 并发访问测试 =====" << std::endl;
    std::cout << "（LRU缓存内置线程安全支持）" << std::endl;

    MemoryCache<int, int> cache(1000, 10);

    const int num_threads = 4;
    const int ops_per_thread = 10000;

    std::cout << "\n启动" << num_threads << "个线程，每个执行"
              << ops_per_thread << "次操作..." << std::endl;

    auto thread_func = [&cache](int thread_id) {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(0, 9999);
        std::uniform_int_distribution<> op_dis(1, 10);

        for (int i = 0; i < ops_per_thread; ++i) {
            int key = dis(gen);
            if (op_dis(gen) <= 7) {  // 70%读取
                int value;
                cache.get(key, value);
            } else {  // 30%写入
                cache.put(key, thread_id * 10000 + key);
            }
        }
    };

    auto start = std::chrono::high_resolution_clock::now();

    std::vector<std::thread> threads;
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back(thread_func, i);
    }

    for (auto& t : threads) {
        t.join();
    }

    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

    std::cout << "\n并发测试完成:" << std::endl;
    std::cout << "  总操作数: " << (num_threads * ops_per_thread) << std::endl;
    std::cout << "  总耗时: " << duration.count() << " ms" << std::endl;
    std::cout << "  吞吐量: " << ((num_threads * ops_per_thread * 1000.0) / duration.count())
              << " ops/sec" << std::endl;

    cache.printStatistics();
}

int main() {
    std::cout << "============================================\n";
    std::cout << "    C++11 高性能缓存系统演示程序            \n";
    std::cout << "============================================\n";

    try {
        // 1. 基础LRU缓存测试
        testBasicLRU();

        // 2. 内存缓存测试
        testMemoryCache();

        // 3. 性能基准测试
        performanceBenchmark();

        // 4. 并发测试
        concurrencyTest();

        std::cout << "\n============================================\n";
        std::cout << "           所有测试完成！                   \n";
        std::cout << "============================================\n";

    } catch (const std::exception& e) {
        std::cerr << "\n错误: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}